package com.cs.beneficios.web.action;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.beneficios.validator.Validaciones;
import com.cs.paoyer.administration.business.model.UserVO;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

import java.sql.Connection;
import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class GuardarProgramaAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
    ActionMessages messages = new ActionMessages();
     try{
      	AccessControl access = new AccessControl();
        access.validateAccess(mapping,request,response);
        String valor1 = null, valor2 = null, valor3 = null, valor4 = null, valor5 = null;
        String valor6 = null, valor7 = null, valor8 = null, valor9 = null, valor10 = null;
        boolean existe = false;
        //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
		ConnectionFactory cf = new ConnectionFactory();
       // database db = new database();
        Validaciones validacion = new Validaciones(cf);
        HttpSession session = request.getSession();
        Connection conn = null;
        try{              
          conn = cf.getConnection();
          //conn = db.getConnectionWithDriver("beneficios","beneficios");
          }
          catch (SQLException e){
        }
          try
              {
                valor1 = request.getParameter("programa");
              }
            catch (Exception e){
                valor1 = "";
              }
            try
            {
              valor2 = request.getParameter("Descripcion");
            }
            catch (Exception e) {
              valor2 = "";
            }
            try  
             {
                valor3 = request.getParameter("Objetivo");
             }
            catch (Exception e){
                valor3 = "";
            }
            try {
              valor4 = request.getParameter("Area");
            }
            catch (Exception e){
              valor4 = "";
            }
            try {
              valor5 = request.getParameter("poblacion");
            }
            catch (Exception e){
              valor5 = "";
            }
            try {
              valor6 = request.getParameter("effectiveFrom");
            }
            catch (Exception e){
              valor6 = "";
            }
            try {
              valor7 = request.getParameter("effectiveUntil");
            }
            catch (Exception e){
              valor7 = "";
            }
            try {
              valor8 = request.getParameter("admincodigo");
            }
            catch (Exception e){
              valor8 = "";
            }
            
         if (valor1 != null){
            existe = validacion.validaprog(valor1.trim());
            try
            {
              cf.closeConnection(validacion.getConn());
            }
            catch (SQLException e)
            {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSSPE - cwsub ********/");
            }
            
              
         }
          
            
        if (!existe){
           //Proceso para la auditoria
            UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
            String terminalAddress = request.getRemoteAddr();
            String strTerminal = ("WEB="+terminalAddress);
            Calendar c = Calendar.getInstance(); 
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
            //Fin del proceso
            
           String strSql = " Insert into tcs_ben_programa (CODIGO,AREA_CODIGO, USU_CODIGO, "+
                        " NOMBRE, DESCRIPCION, OBJETIVO,POBLACION_OBJETIVO,DESDE_VIGENCIA,HASTA_VIGENCIA,VIGENCIA, "+
                        " usuario_crea, fecha_crea, terminal_crea, usuario_modifica, fecha_modifica, terminal_modifica) "+
                        " values (SCS_BEN_PRG.NEXTVAL,?,?,upper(?),upper(?),upper(?),upper(?),to_date(?,'yyyy-mm-dd'),to_date(?,'yyyy-mm-dd'),'A',?,to_date(?,'dd/mm/yyyy'),?,?,to_date(?,'dd/mm/yyyy'),?) ";
            String strPar[] = {valor4,valor8,valor1.trim(),valor2,valor3,valor5,valor6,valor7,user.getName(), dateFormat.format(c.getTime()),strTerminal,user.getName(),dateFormat.format(c.getTime()),strTerminal};
          
           try{
              int insertar = cf.execSql(strSql,strPar,conn);
              if(insertar > 0)
              {
                session.setAttribute("mensajes","El programa fue creado con Exito!!!");
                session.setAttribute("primeraVez",null);
              }
             }
             catch(SQLException e)
             {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSSPE - cwsub ********/");
                session.setAttribute("mensajes","El programa no se pudo crear.");
                session.setAttribute("primeraVez",null);
             }
             
          }else{
              session.setAttribute("mensajes","El programa ya existe.");
              session.setAttribute("primeraVez",null);
          }
          
        try
        {
          cf.closeConnection(conn);
        }catch(SQLException e)
        {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
        }
     }catch(UserException ue){
        messages.add("msgWarn",  new ActionMessage("loginForm.message."
																			+ ue.getExceptionVO().getId()));
				saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
   }
    return mapping.findForward("success");
  }
}